﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Inventory_StockTransfer : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            if(! IsPostBack)
                 ResetForm();
        }
        
    }
    private void ResetForm()
    {
        try
        {
            ////Cửa hàng chuyển
            //string strShopID = string.Empty;
            ////if (Session["RoleID"] == null || Session["RoleID"].ToString() == "1")
            
            //strShopID = Session["ShopID"].ToString();
            ////else strShopID = Session["ShopID"].ToString();
            //Utils.loadShopToCombo(cbFromShop, 0, Convert.ToInt32(strShopID));

            //Utils.loadShopToComboExcludeID(cbToShop, 0, 0, "S");
            //if (strShopID == "0")
            //{
            //    Utils.loadShopToComboSearch(cbFromShopSearch, 1, Convert.ToInt32(strShopID));//Có tất cả
            //}
            //else
            //{
            //    Utils.loadShopToComboSearch(cbFromShopSearch, 0, Convert.ToInt32(strShopID));// Không có tất cả
            //}
            
            //Load Tinh thanh
            loadProvince();
           
            //Cửa hàng nhận
            //Utils.loadShopToCombo(cbToShop, 0, 0, "S");
            
            
            gvProduct.DataSource = new DataTable();
            gvProduct.DataBind();
            rdpTransferDate.SelectedDate = DateTime.Now.Date;
            rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToDateSearch.SelectedDate = DateTime.Now.Date;
            txtTransferWarehouseCode.Text = GernerateCode();
            //Button
            btnCancel.Enabled = false;
            btnExport.Enabled = false;
            btnDel.Enabled = false;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-loadForm:" + ex.Message);
        }
    }
    private void resetGrid()
    {
        ViewState["TBLTransferWarehouseDetail"] = null;
        divTotalQuantity.InnerText = "Tổng số lượng: 0";
        divTotalWeight.InnerText = "Tổng trọng lượng: 0 Kg";
        divGetTotalQuantity.InnerText = "";
        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
        divGetTotalAmount.InnerText = "";
        
        gvProduct.DataSource = new DataTable();
        gvProduct.DataBind();
        txtQuantity.Text = "";
    }
    private void loadProductOfWarehouse()
    {
        try
        {
           
            db = new DBDataContext();
            string strShopID = cbFromShop.SelectedValue.ToString();
            string strProductType = cbType.SelectedValue.ToString();
            strShopID = strShopID == "" ? "-1" : strShopID;
            cbProduct.Items.Clear();
            if (strProductType == "R") {
                var listProduct = (from a in db.Warehouses
                                   join b in db.Products on a.ProductID equals b.ID
                                   join c in db.CodeDetails on a.PackType.ToString() equals c.CDCode
                                   where a.Status == 'A' && a.Quantity > 0 && a.ShopID == Convert.ToInt32(strShopID) && b.ProductType == strProductType
                                   orderby b.ProductName
                                   select new
                                   {
                                       ProductName = b.ProductName,
                                       ProductID = b.ID +"|"+ a.PackType,
                                       PackTypeName = c.CDName,
                                       PackType = a.PackType,
                                       ProductCode = b.ProductCode,
                                       PurchasePrice = a.PurchasePrice,
                                       ProductType = b.ProductType,
                                       Quantity = a.Quantity
                                   }
                ).ToList();
                foreach (var p in listProduct)
                {
                    RadComboBoxItem ra = new RadComboBoxItem();
                    if (p.Quantity > 0)
                    {
                        ra.Text = p.ProductCode + "-" + p.ProductName + " (" + p.PackTypeName + " -SL tồn kho " + p.Quantity + ")";
                        ra.Value = p.ProductID.ToString();
                        cbProduct.Items.Add(ra);
                    }
                }
                DataTable dt = listProduct.ToDataTable();
                if (dt.Rows.Count > 0)
                    ViewState["dtWarehouse"] = dt;
            }
            if (strProductType == "P") 
            {
                 var listProduct= (from a in db.Warehouses
                 join b in db.Products on a.ProductID equals b.ID
                 where a.Status == 'A' && a.ShopID == Convert.ToInt32(strShopID) && a.Quantity > 0 && b.ProductType == strProductType
                 orderby b.ProductName
                 select new
                 {
                     ProductName = b.ProductName,
                     ProductID = b.ID   + "|0",
                     PackTypeName = "",
                     PackType = "0",
                     ProductCode = b.ProductCode,
                     PurchasePrice = a.PurchasePrice,
                     ProductType = b.ProductType,
                     Quantity = a.Quantity
                 }).ToList();

                foreach (var p in listProduct)
                {
                    RadComboBoxItem ra = new RadComboBoxItem();
                    if (p.Quantity > 0)
                    {
                        ra.Text = p.ProductCode + "-" + p.ProductName + "(SL tồn kho " + String.Format("{0:N0}", p.Quantity) + ")";
                        ra.Value = p.ProductID.ToString();
                        cbProduct.Items.Add(ra);
                    }
                }
                DataTable dt = listProduct.ToDataTable();
                if (dt.Rows.Count > 0)
                    ViewState["dtWarehouse"] = dt;
            }
            
            
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-loadProductOfWarehouse-Username:"+ Session["Username"].ToString() +"-Error:" + ex.Message);
            ResetForm();
        }
    }
    private void getDataSearch()
    {
        ProStockTransfer pro = new ProStockTransfer();
        pro.strTransferOrderCodeSearch = Utils.KillChars(txtTransferWarehouseCodeSearch.Text.Trim());
        pro.strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        pro.iFromShopIDSearch = Convert.ToInt32(Utils.KillChars(cbFromShopSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbFromShopSearch.SelectedValue.Trim().ToString()));
        pro.iProvinceIDSearch = Convert.ToInt32(Utils.KillChars(cbProvinceSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbProvinceSearch.SelectedValue.Trim().ToString()));
        pro.iToShopIDSearch = Convert.ToInt32(Utils.KillChars(cbToShopSearch.SelectedValue.Trim().ToString() == "0" ? "-1" : cbToShopSearch.SelectedValue.Trim().ToString()));
        pro.strStatusSearch = Utils.KillChars(cbStatusSearch.SelectedValue.Trim().ToString());
        pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));

        loadData(pro);
    }
    private DataTable DTTransferWarehouseDetail(int ID = 0)
    {
        //DataTable dt = null;
        try
        {
            db = new DBDataContext();
            var dtPurchaseOrderDetail = (from a in db.TransferWarehouseDetails
                                         join b in db.Products on a.ProductID equals b.ID
                                         where a.TransferWarehouseID == ID && a.Status == 'A' && b.Status == 'A'
                                         select new
                                         {
                                             ProductID = b.ID + "|"  + a.PackType,
                                             ProductName = b.ProductCode + "-" + b.ProductName + (a.PackType == 0 ? "":  " (" + a.PackType + " Kg)"),
                                             PurchasePrice = Convert.ToDouble(a.PurchasePrice),
                                             Amount = Convert.ToDouble(a.Amount),
                                             Quantity = Convert.ToInt32(a.Quantity),
                                             Weight = a.PackType == 0 ? a.Quantity : (a.PackType * a.Quantity)
                                         }).ToList();


            return dtPurchaseOrderDetail.ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-DTShopLocation-Username:"+ Session["Username"].ToString() + "-Error:" + ex.Message.ToString());
            return new DataTable();
        }

    }
    private void loadData(ProStockTransfer pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramPurchaseOrderID = helper.Parameter;
            paramPurchaseOrderID.ParameterName = "TransferWarehouseID";
            paramPurchaseOrderID.DbType = DbType.Int32;
            paramPurchaseOrderID.Value = -1;
            helper.AddParameter(paramPurchaseOrderID);

            System.Data.Common.DbParameter paramCode = helper.Parameter;
            paramCode.ParameterName = "TransferWarehouseCode";
            paramCode.DbType = DbType.String;
            paramCode.Value = pro.strTransferOrderCodeSearch;
            helper.AddParameter(paramCode);
            

            System.Data.Common.DbParameter ProvinceID = helper.Parameter;
            ProvinceID.ParameterName = "ProvinceID";
            ProvinceID.DbType = DbType.Int32;
            ProvinceID.Value = pro.iProvinceIDSearch;
            helper.AddParameter(ProvinceID);

            System.Data.Common.DbParameter paramFromShopID = helper.Parameter;
            paramFromShopID.ParameterName = "FromShopID";
            paramFromShopID.DbType = DbType.Int32;
            paramFromShopID.Value = pro.iFromShopIDSearch;
            helper.AddParameter(paramFromShopID);

            System.Data.Common.DbParameter paramToShopID = helper.Parameter;
            paramToShopID.ParameterName = "ToShopID";
            paramToShopID.DbType = DbType.Int32;
            paramToShopID.Value = pro.iToShopIDSearch;
            helper.AddParameter(paramToShopID);

            System.Data.Common.DbParameter paramStatus = helper.Parameter;
            paramStatus.ParameterName = "Status";
            paramStatus.DbType = DbType.String;
            paramStatus.Value = pro.strStatusSearch;
            helper.AddParameter(paramStatus);


            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetTransferWarehouse", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}",dt.Rows[0]["TotalRows"]);
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-loadData-Username:" + Session["Username"].ToString() +"-Error:" + ex.Message);
        }
    }
    private void fillData(ProStockTransfer pro)
    {
        try
        {
            txtTransferWarehouseCode.Text = pro.strTransferOrderCode;
            cbFromShop.SelectedValue = pro.iFromShopID.ToString();
            cbToShop.SelectedValue = pro.iToShopID.ToString();
            cbType.SelectedValue = pro.strType;
            rdpTransferDate.SelectedDate = pro.dateTimeTransferDate;
            txtStatus.Text = pro.strStatusName;
            txtRemark.Text = pro.strRemark;
            txtExportedEmployee.Text = pro.strExportedEmployee;
            txtExportedDate.Text = pro.strExportedDate;
            loadProductOfWarehouse();
            if (ViewState["TransferWarehouseID"] != null)
            {
                DataTable dt = DTTransferWarehouseDetail(Convert.ToInt32(ViewState["TransferWarehouseID"]));
                if (dt.Rows.Count > 0)
                {
                    ViewState["TBLTransferWarehouseDetail"] = dt;
                    Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                    divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                    divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                    divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                    
                    Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                    divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                    divGetTotalAmount.InnerText = iTotalAmount.ToString();
                }
                else {

                    divTotalQuantity.InnerText = "Tổng số lượng: 0";
                    divTotalWeight.InnerText = "Tổng trọng lượng: 0 kg";
                    divGetTotalQuantity.InnerText = "";
                    divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                    divGetTotalAmount.InnerText = "";
                }
                if (pro.strType == "P")
                    divTotalWeight.Visible = false;
                gvProduct.DataSource = dt;
                gvProduct.DataBind();
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
            }

            SetStatus(pro.strStatus);


        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-fillData-Username:" +Session["Username"].ToString() +"-Error:" + ex.Message);
        }
    }
    private DataTable createTable()
    {
        DataTable dt = null;
        try
        {
            if (ViewState["TBLTransferWarehouseDetail"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.String"));
                dt.Columns.Add("PackType", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("PurchasePrice", System.Type.GetType("System.Double"));
                dt.Columns.Add("Quantity", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));
                //dt.Columns.Add("Delete");
            }
            else dt = (DataTable)ViewState["TBLTransferWarehouseDetail"];
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-createTable-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message.ToString());
        }
        return dt;
    }
    private void addDataToTable()
    {
        try
        {
            DataTable dt = createTable();
            //check ma san pham da chon chua, neu đa ton tai thi update
            DataRow[] rowArr = dt.Select("ProductID='" + cbProduct.SelectedValue.ToString() + "'");
            if (rowArr.Count() > 0)
            {
                //string[] arr = cbProduct.SelectedValue.ToString().Split('|');
                //DataRow row = rowArr[0];
                //row["PurchasePrice"] = Utils.KillChars(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //int iQuantity = Convert.ToInt32(row["Quantity"]) + Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
                //row["Quantity"] = iQuantity;
                //row["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
                //Double iAmount = iQuantity * Convert.ToDouble(txtPurchasePrice.Text.Trim().Replace(",", ""));
                //row["Amount"] = iAmount;
                DataRow row = rowArr[0];
                row.Delete();
                dt.AcceptChanges();
            }
            DataRow drNew = dt.NewRow();
            string[] arr = cbProduct.SelectedValue.ToString().Split('|');

            //drNew["ProductID"] = cbProduct.SelectedValue.ToString();
            //drNew["ProductName"] = hidProductName.Value.ToString();
            //drNew["PurchasePrice"] = Utils.KillChars(hidPurchasePrice.Value.Trim().Replace(",", ""));
            //drNew["Weight"] = Utils.KillChars(txtQuantity.Text.Trim().Replace(",", ""));
            //Double iAmount = Convert.ToDouble(txtQuantity.Text.Trim().Replace(",", "")) * Convert.ToDouble(hidPurchasePrice.Value.Trim().Replace(",", ""));
            //drNew["Amount"] = iAmount;
            //dt.Rows.Add(drNew);

            drNew["ProductID"] = cbProduct.SelectedValue.ToString();
            drNew["PackType"] = arr[1];
            drNew["ProductName"] = cbProduct.SelectedItem.Text.Trim();
            drNew["PurchasePrice"] = Utils.KillChars(hidPurchasePrice.Value.Trim().Replace(",", ""));
            int iQuantity = Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
            drNew["Quantity"] = iQuantity;
            drNew["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
            Double iAmount = Convert.ToInt32(txtQuantity.Text.Trim().Replace(",", "")) * Convert.ToDouble(hidPurchasePrice.Value.Trim().Replace(",", ""));
            drNew["Amount"] = iAmount;
            dt.Rows.Add(drNew);
            
            ViewState["TBLTransferWarehouseDetail"] = dt;
            //Double iTotalWeight = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Weight"])));
            //divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", iTotalWeight) + " kg";

            //divGetTotalQuantity.InnerText = iTotalWeight.ToString();
            //Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
            //divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
            //divGetTotalAmount.InnerText = iTotalAmount.ToString();
            if (dt.Rows.Count > 0)
            {
                Double iTotalQuantity = Convert.ToInt32(dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Quantity"])));
                divTotalQuantity.InnerText = "Tổng số lượng: " + String.Format("{0:#,#.##}", iTotalQuantity);
                divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:#,#.##}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";
                
                Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                divTotalAmount.InnerText = "Tổng tiền: " + String.Format("{0:#,#.##}", iTotalAmount) + " VNĐ";
                divGetTotalAmount.InnerText = iTotalAmount.ToString();
            }
            else
            {
                divTotalQuantity.InnerText = "Tổng số lượng: 0";
                divTotalWeight.InnerText = "Tổng trọng lượng: 0 kg";
                divGetTotalQuantity.InnerText = "";
                divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                divGetTotalAmount.InnerText = "";
            }
            if (arr[1] == "0")
                divTotalWeight.Visible = false;
            gvProduct.DataSource = dt;
            gvProduct.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-addDataToTable-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message.ToString());
        }
    }
    private string GernerateCode()
    {
        string strCode = string.Empty;
        try
        {
            //Fortmat: LC00000001
            /*
         
              int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
                int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
                String LastCode = ("000000" + MaxOrderNumber).ToString();
                String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
             */

            db = new DBDataContext();
            var PurchaseOrderMax = db.TransferWarehouses.Max(d => d.OrderNumber);
            int MaxOrderNumber = (PurchaseOrderMax == null ? 0 : Convert.ToInt32(PurchaseOrderMax)) + 1;
            String strLastCode = "00000000" + MaxOrderNumber.ToString();
            strCode = "LC" + strLastCode.Substring(strLastCode.Length - 8);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-GernerateCode-Username:" + Session["Usernam"].ToString() +"-Error:" + ex.Message);
            ResetForm();
        }
        return strCode;
    }
    private void SetStatus(string strStatus)
    {
        if (strStatus == "T" || strStatus == "E" || strStatus == "R" || strStatus == "F")//Da Xuat kho
        {
            //Button
            /**
             * N: Tạo mới, E: hủy bỏ, T: Đã xuất kho, I: Xóa,  F: Hoàn tất(Xác nhận)
             * 
             */
            btnExport.Enabled = false;
            btnAdd.Enabled = false;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
            btnDel.Enabled = false;
            btnCancel.Enabled = true;
            txtDeliveryPerson.ReadOnly = true;
            gvProduct.Enabled = false;
            if (strStatus == "F" || strStatus == "E")
            {
                btnCancel.Enabled = false;
                rdpTransferDate.Enabled = false;
            }
            
            //Combo
            cbType.Enabled = false;
            cbToShop.Enabled = false;
            cbFromShop.Enabled = false;
            cbProvince.Enabled = false;
        }
        
        if (strStatus == "N")
        {// Tao moi 
            btnCancel.Enabled = false;
            btnExport.Enabled = true;
            btnAdd.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = true;
            //Combo
            cbToShop.Enabled = false;
            cbFromShop.Enabled = false;
            cbType.Enabled = false;
            cbProvince.Enabled = false;
        }
    }
    private bool save(ProStockTransfer pro)
    {
        db = new DBDataContext();
        db.Connection.Open();
        try
        {
            if (ViewState["TransferWarehouseID"] == null)//Insert INTO PurChaseOrder
            {
                using (var transation = new TransactionScope())
                {
                    try
                    {
                        string strCode = GernerateCode();
                        TransferWarehouse obj = new TransferWarehouse();
                        obj.TransferWarehouseCode = strCode;
                        obj.OrderNumber = Convert.ToInt32(Utils.KillChars(strCode.Substring(2, strCode.Length - 2)));
                        obj.TransferDate = pro.dateTimeTransferDate;
                        obj.FromShopID = pro.iFromShopID;
                        obj.ToShopID = pro.iToShopID;
                        obj.TotalAmount = pro.dTotalAmount;
                        obj.TotalQuantity = pro.iTotalQuanity;
                        obj.ProductType = pro.strType;
                        obj.DeliveryPerson = pro.strDeliveryPerson;
                        obj.Remark = pro.strRemark;
                        obj.CreatedBy = Session["Username"].ToString();
                        obj.CreatedDateTime = DateTime.Now;
                        obj.LastUpdatedBy = Session["Username"].ToString();
                        obj.LastUpdatedDateTime = DateTime.Now;
                        obj.Status = Convert.ToChar(pro.strStatus);
                        db.Insert<TransferWarehouse>(obj);
                        db.SubmitChanges();

                        ViewState["TransferWarehouseID"] = obj.ID;
                        //Insert TransferWarsehouseDetail
                        db.Insert<TransferWarehouseDetail>(insertTransferWarsehouseDetail(Convert.ToInt32(ViewState["TransferWarehouseID"])));
                        db.SubmitChanges();
                        transation.Complete();

                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockTransfer Page-Save-Transation-Status:N-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message);
                        transation.Dispose();
                        ViewState["TransferWarehouseID"] = null;
                        return false;
                    }
                }

            }
            else
            {
                TransferWarehouse obj = db.TransferWarehouses.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["TransferWarehouseID"]));

                obj.Remark = pro.strRemark;
                obj.LastUpdatedBy = Session["Username"].ToString();
                obj.LastUpdatedDateTime = DateTime.Now;
                if (pro.strStatus == "T")//Tinh trang Xuat kho
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            obj.TotalAmount = pro.dTotalAmount;
                            obj.TotalQuantity = pro.iTotalQuanity;
                            obj.DeliveryPerson = pro.strDeliveryPerson;
                            obj.TransferDate = Convert.ToDateTime(Utils.KillChars(rdpTransferDate.SelectedDate.ToString()));
                            //db.SubmitChanges();
                            //Delete du lieu cu
                            deleteDetail(Convert.ToInt32(ViewState["TransferWarehouseID"]));
                            //Insert TransferWarsehouseDetail
                            db.Insert<TransferWarehouseDetail>(insertTransferWarsehouseDetail(Convert.ToInt32(ViewState["TransferWarehouseID"])));
                            //db.SubmitChanges();

                            
                            obj.Status = Convert.ToChar(pro.strStatus);
                            obj.DeliveryPerson = pro.strDeliveryPerson;
                            obj.ExportedDate = DateTime.Now;
                            obj.ExportedEmployee = Session["Username"].ToString();
                            //obj.Remark = pro.strRemark;
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("StockTransfer Page-Save-Transation-Status-T-TransferWarehouseID-" + ViewState["TransferWarehouseID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            //ViewState["PurchaseOrderID"] = null;
                            return false;
                        }
                    }
                }
                if (pro.strStatus == "N")//Tao moi
                {
                    using (var transation = new TransactionScope())
                    {
                        try
                        {
                            obj.TotalAmount = pro.dTotalAmount;
                            obj.TotalQuantity = pro.iTotalQuanity;
                            obj.TransferDate = Convert.ToDateTime(Utils.KillChars(rdpTransferDate.SelectedDate.ToString()));
                            //db.SubmitChanges();
                            //Delete du lieu cu
                            deleteDetail(Convert.ToInt32(ViewState["TransferWarehouseID"]));
                            //Insert lai moi
                            db.Insert<TransferWarehouseDetail>(insertTransferWarsehouseDetail(Convert.ToInt32(ViewState["TransferWarehouseID"])));
                            db.SubmitChanges();
                            transation.Complete();
                        }
                        catch (Exception ex)
                        {
                            ControlUtil.LogError("StockTransfer Page-Save-Transation-Status-N-TransferWarehouseID-" + ViewState["TransferWarehouseID"].ToString() + ":" + ex.Message);
                            transation.Dispose();
                            //ViewState["PurchaseOrderID"] = null;
                            return false;
                        }
                    }
                }
                if (pro.strStatus == "E")//Huy don hang
                {
                    obj.Status = 'E';
                    db.SubmitChanges();
                }
            }
            db.Connection.Close();
            return true; 
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-Save:" + ex.Message);
            return false;
        }
        finally
        {
            db.Connection.Close();
        }
    }
    private void deleteDetail(int iID = 0)
    {
        try
        {
            if (iID != 0)
            {
                List<TransferWarehouseDetail> soDetail = (from sd in db.TransferWarehouseDetails where sd.TransferWarehouseID == iID select sd).ToList<TransferWarehouseDetail>();
                db.Delete<TransferWarehouseDetail>(soDetail);
                db.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-deletePurchaseOrderDetail:" + ex.Message.ToString());
        }
    }
    private List<TransferWarehouseDetail> insertTransferWarsehouseDetail(int iTransferWarsehouseDetail = 0)
    {
        try
        {
            List<TransferWarehouseDetail> listDetail = new List<TransferWarehouseDetail>();
            foreach (GridDataItem item in gvProduct.Items)
            {
                string[] arr = Utils.KillChars(item["ProductID"].Text.Trim()).Split('|');
                TransferWarehouseDetail soDetail = new TransferWarehouseDetail();
                soDetail.TransferWarehouseID = iTransferWarsehouseDetail;
                soDetail.ProductID = Convert.ToInt32(arr[0]);
                soDetail.PackType = Convert.ToInt32(arr[1]);//PackType
                string strPurchasePrice = Utils.KillChars(((Label)(item.FindControl("lblPurchasePrice"))).Text.Trim().Replace(",", ""));
                soDetail.PurchasePrice = Convert.ToDouble(strPurchasePrice == "" ? "0" : strPurchasePrice);
                string stQuantity = Utils.KillChars(((Label)(item.FindControl("lblQuantity"))).Text.Trim().Replace(",", ""));
                soDetail.Quantity = Convert.ToInt32(stQuantity == "" ? "0" : stQuantity);
                string strAmount = Utils.KillChars(((Label)(item.FindControl("lblAmount"))).Text.Trim().Replace(",", ""));
                soDetail.Amount = Convert.ToDouble(strAmount == "" ? "0" : strAmount);
                soDetail.CreatedBy = Session["UserName"].ToString();
                soDetail.LastUpdatedBy = Session["UserName"].ToString();
                soDetail.CreatedDateTime = DateTime.Now;
                soDetail.LastUpdatedDateTime = DateTime.Now;
                soDetail.Status = 'A';
                listDetail.Add(soDetail);
            }
            return listDetail;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-insertPurchaseOrderDetail:" + ex.Message);
            return null;
        }
    }
    private void delete(int ID)
    {
        db = new DBDataContext();

        TransferWarehouse obj = db.TransferWarehouses.FirstOrDefault(x => x.ID == ID);
        obj.LastUpdatedDateTime = DateTime.Now;
        obj.LastUpdatedBy = Session["Username"].ToString();
        obj.Status = 'I';
        db.Update<TransferWarehouse>(obj);
        db.SubmitChanges();
        db.Connection.Close();

    }
    private void loadProvince()
    {
        try
        {
            //Load tinh thanh 
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
            Utils.loadLocation(cbProvince, 0, isProvinceAll, ProvinceID);//Tao moi
            Utils.loadLocationSearch(cbProvinceSearch, 0, isProvinceAll, ProvinceID);//Search
            //Load shop
            loadShop(ProvinceID, ProvinceID);

        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-LoadProvince:" + ex.Message);
        }
    }
    private void loadShop(int ProvinceID = -1, int ProvinceIDSearch = -1)
    {
        try
        {
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cbFromShop, isShopAll, ProvinceID, ShopID, "");//Tạo mới
            Utils.loadShopToComboExcludeID(cbToShop, 1, Convert.ToInt32(cbFromShop.SelectedValue.ToString()), "");//Tạo mới

            Utils.loadShopByProvinceToComboSearch(cbFromShopSearch, isShopAll, ProvinceIDSearch, ShopID, "");//Tìm kiếm
            Utils.loadShopToComboExcludeSearch(cbToShopSearch, 1, Convert.ToInt32(cbFromShopSearch.SelectedValue.ToString()), "");//Tìm kiếm
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-loadShop:" + ex.Message);
        }
    }
    protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        loadProductOfWarehouse();
        resetGrid();

    }
    protected void cbProvince_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (!cbProvince.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvince.SelectedValue.Trim()))//Tao moi
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
        //Tim kiem
        if (!cbProvinceSearch.SelectedValue.Trim().Equals("0") && !string.IsNullOrEmpty(cbProvinceSearch.SelectedValue.Trim()))
            loadShop(Convert.ToInt32(cbProvince.SelectedValue.Trim()), Convert.ToInt32(cbProvinceSearch.SelectedValue.Trim()));
    }
    protected void cbFromShop_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        //Load cua hang den
        if (!string.IsNullOrEmpty(cbFromShop.SelectedValue.ToString()))
        {
            Utils.loadShopToComboExcludeID(cbToShop, 1, Convert.ToInt32(cbFromShop.SelectedValue.ToString()), "");
            //Load Product
            loadProductOfWarehouse();
            resetGrid();
        }
        if (!string.IsNullOrEmpty(cbToShopSearch.SelectedValue.ToString()))
        {
            Utils.loadShopToComboExcludeSearch(cbToShopSearch, 1, Convert.ToInt32(cbFromShopSearch.SelectedValue.ToString()), "");
            
        }
        
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (string.IsNullOrEmpty(cbProduct.SelectedValue))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtQuantity.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng!");
                    txtQuantity.Focus();
                    return;
                }
                if (txtQuantity.Text.Trim() == "0")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng nhập phải lớn hơn 0!");
                    txtQuantity.Focus();
                    return;
                }


                //Lay thong tin san pham
                if (ViewState["dtWarehouse"] != null)//Lay thong tin gia, check ton kho
                {
                    DataTable dt = (DataTable)ViewState["dtWarehouse"];
                    string strProductID = cbProduct.SelectedValue;
                    string iCount = dt.Rows.Count.ToString();
                    if (dt.Rows.Count > 0)
                    {
                        DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                        if (rowArr.Count() > 0)
                        {
                            DataRow row = rowArr[0];
                            //if (ViewState["TBLTransferWarehouseDetail"] == null)
                            hidQuantity.Value = row["Quantity"].ToString();
                            //else
                            //{
                            //    //Lay Tong Quantity dang co tren Grid theo ProductID
                            //    DataTable dtTransferWarehouseDetail = (DataTable)ViewState["TBLTransferWarehouseDetail"];
                            //    DataRow[] rowArr2 = dtTransferWarehouseDetail.Select("ProductID='" + strProductID + "'");
                            //    if (rowArr2.Count() > 0)//San pham da ton tai san tren Grid
                            //    {
                            //        DataRow row2 = rowArr2[0];
                            //        // Lay tong Quantity dang co
                            //        hidQuantity.Value = (Convert.ToDouble(row["Quantity"]) - Convert.ToDouble(row2["Quantity"])).ToString();//Lay tong Quantity hien co tren Grid theo ProductID
                            //    }
                            //    else
                            //    {
                            //        hidQuantity.Value = row["Quantity"].ToString();//Chưa ton tai tren Grid
                            //    }
                            //}
                            hidPurchasePrice.Value = row["PurchasePrice"].ToString();//Lay gia san pham
                            hidProductName.Value = row["ProductCode"].ToString() + "-" + row["ProductName"].ToString();
                        }
                    }

                }
                if (Convert.ToInt32(txtQuantity.Text.ToString().Replace(",", "")) > Convert.ToInt32(hidQuantity.Value))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng nhập không lớn hơn số lượng tồn kho!");
                    txtQuantity.Focus();
                    return;
                }
                addDataToTable();
                div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
                cbProduct.Enabled = true;
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockTransfer Page-btnAdd_Click:" + ex.Message);
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Thêm không thành công, vui lòng thực hiện lại!");
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                ProStockTransfer pro = new ProStockTransfer();

                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "TransferWarehouseID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetTransferWarehouse", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            pro.strTransferOrderCode = dt.Rows[0]["TransferWarehouseCode"].ToString();
                            pro.iFromShopID = Convert.ToInt32(dt.Rows[0]["FromShopID"].ToString());
                            pro.iToShopID = Convert.ToInt32(dt.Rows[0]["ToShopID"].ToString());
                            pro.strType = dt.Rows[0]["ProductType"].ToString();
                            pro.strStatus = dt.Rows[0]["Status"].ToString();
                            pro.dateTimeTransferDate = Convert.ToDateTime(dt.Rows[0]["TransferDate"].ToString());
                            pro.strStatusName = dt.Rows[0]["StatusName"].ToString();
                            pro.dTotalAmount = Convert.ToDouble(dt.Rows[0]["TotalAmount"].ToString());
                            pro.iTotalQuanity = Convert.ToInt32(dt.Rows[0]["TotalQuantity"].ToString());
                            pro.strDeliveryPerson = dt.Rows[0]["DeliveryPerson"].ToString();
                            pro.strRemark = dt.Rows[0]["Remark"].ToString();
                            pro.strExportedEmployee = dt.Rows[0]["ExportedEmployee"].ToString();
                            pro.strExportedDate = dt.Rows[0]["ExportedDate"].ToString();
                            pro.LastUpdatedBy = dt.Rows[0]["LastUpdatedBy"].ToString();
                            pro.LastUpdatedDateTime = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["TransferWarehouseID"] = ID;
                            fillData(pro);

                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand-EditItem-Username:" + Session["Username"].ToString() + "-TransferWarehouseID:" + ID.ToString() + "-Error:" + ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 3;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void gvProduct_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;
            string strProductID = e.CommandArgument.ToString();//Lay ID 
            if (commandName == "EditItem")
            {
                try
                {
                    DataTable dt = (DataTable)ViewState["TBLTransferWarehouseDetail"];
                    DataRow[] rows = dt.Select("ProductID='" + strProductID + "'");
                    if (rows.Count() > 0)
                    {
                        DataRow row = rows[0];
                        txtQuantity.Text = String.Format("{0:N0}", row["Quantity"]);
                        cbProduct.SelectedValue = strProductID.ToString();
                        cbProduct.Enabled = false;
                        ViewState["TBLTransferWarehouseDetail"] = dt;
                        div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
                        gvProduct.DataSource = dt;
                        gvProduct.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("StockTransfer Page-gvProduct_ItemCommand-EditItem:" + ex.Message);
                }
            }

            else if (commandName == "DeleteItem")
            //if (commandName == "DeleteItem")
            {
                try
                {
                    DataTable dt = (DataTable)ViewState["TBLTransferWarehouseDetail"];
                    DataRow[] rowArr = dt.Select("ProductID='" + strProductID + "'");
                    if (rowArr.Count() > 0)
                    {
                        //string[] arr = cbProduct.SelectedValue.ToString().Split('|');
                        //DataRow row = rowArr[0];
                        //row["PurchasePrice"] = Utils.KillChars(txtPurchasePrice.Text.Trim().Replace(",", ""));
                        //int iQuantity = Convert.ToInt32(row["Quantity"]) + Convert.ToInt32(Utils.KillChars(txtQuantity.Text.Trim().Replace(",", "")));
                        //row["Quantity"] = iQuantity;
                        //row["Weight"] = iQuantity * Convert.ToInt32(arr[1]);
                        //Double iAmount = iQuantity * Convert.ToDouble(txtPurchasePrice.Text.Trim().Replace(",", ""));
                        //row["Amount"] = iAmount;
                        
                        DataRow row = rowArr[0];
                        if (row["PackType"] == "0")
                            divTotalWeight.Visible = false;
                        row.Delete();
                        dt.AcceptChanges();
                        
                    }
                    ViewState["TBLTransferWarehouseDetail"] = dt;
                    if (dt.Rows.Count > 0)
                    {
                        Double iTotalQuantity = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Quantity"])));
                        divTotalQuantity.InnerHtml = "Tổng số lượng: " + String.Format("{0:N0}", iTotalQuantity);
                        divGetTotalQuantity.InnerText = iTotalQuantity.ToString();
                        divTotalWeight.InnerText = "Tổng trọng lượng: " + String.Format("{0:N0}", dt.AsEnumerable().Sum(dr => Convert.ToInt32(dr["Weight"]))) + " Kg";

                        Double iTotalAmount = Convert.ToDouble(dt.AsEnumerable().Sum(dr => Convert.ToDouble(dr["Amount"])));
                        divTotalAmount.InnerHtml = "Tổng tiền: " + String.Format("{0:N0}", iTotalAmount) + " VNĐ";
                        divGetTotalAmount.InnerText = iTotalAmount.ToString();
                    }
                    else
                    {
                        divTotalQuantity.InnerText = "Tổng số lượng: 0";
                        divTotalWeight.InnerText = "Tổng trọng lượng: 0 kg";
                        divGetTotalQuantity.InnerText = "";
                        divTotalAmount.InnerText = "Tổng tiền: 0 VNĐ";
                        divGetTotalAmount.InnerText = "";
                    }
                    div_TotalProduct.InnerText = "Tổng cộng sản phẩm: " + String.Format("{0:N0}",gvProduct.Items.Count);
                    gvProduct.DataSource = dt;
                    gvProduct.DataBind();
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("StockTransfer Page-gvProduct_ItemCommand-DeleteItem-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message);
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockTransfer Page-gvProduct_ItemCommand:" + ex.Message);
        }
    }
    #region Properties
    public class ProStockTransfer
    {
        public string strTransferOrderCode { get; set; }
        public DateTime dateTimeTransferDate { get; set; }
        public string strRemark { get; set; }
        public string strType { get; set; }
        public int? iFromShopID { get; set; }
        public int? iToShopID { get; set; }
        public string strFromShopName { get; set; }
        public string strDeliveryPerson { get; set; }
        public string strExportedEmployee { get; set; }
        public string ImportedEmployee { get; set; }
        public string strExportedDate { get; set; }
        public string LastUpdatedBy { get; set; }
        public string LastUpdatedDateTime { get; set; }   
        public int? iOrderNumber { get; set; }
        public string strStatus { get; set; }
        public string strStatusName { get; set; }
        public int? iPurchaseOrderPrice { get; set; }
        public int? iAmount { get; set; }
        public double? dTotalAmount { get; set; }
        public Int32? iTotalQuanity { get; set; }
        public string strStartDate { get; set; }
        public int? iPackType { get; set; }
        public string strEndDate { get; set; }
        public string strTypeSearch { get; set; }
        public int? iFromShopIDSearch { get; set; }
        public int? iToShopIDSearch { get; set; }
        public int? iProvinceIDSearch { get; set; }
        public string strTransferOrderCodeSearch { get; set; }
        public string strStatusSearch { get; set; }
    }
    #endregion End Properties
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("/StockTransfer", false);
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            #region Validate Input
            if (String.IsNullOrWhiteSpace(rdpTransferDate.SelectedDate.ToString()))
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn ngày nhập đơn hàng!");
                rdpTransferDate.Focus();
                return;
            }
            if (String.IsNullOrWhiteSpace(cbToShop.SelectedValue))
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng chuyển!");
                cbToShop.Focus();
                return;
            }
            if (String.IsNullOrWhiteSpace(cbFromShop.SelectedValue))
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng chuyển!");
                cbFromShop.Focus();
                return;
            }
            if (String.IsNullOrWhiteSpace(cbToShop.SelectedValue))
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng đến!");
                cbToShop.Focus();
                return;
            }
            if (String.IsNullOrWhiteSpace(cbType.SelectedValue))
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại gạo!");
                cbType.Focus();
                return;
            }
            if (gvProduct.Items.Count == 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng thêm chi tiết sản phẩm!");
                cbProduct.Focus();
                return;
            }
            #endregion

            ProStockTransfer pro = new ProStockTransfer();
            pro.dateTimeTransferDate = Convert.ToDateTime(Utils.KillChars(rdpTransferDate.SelectedDate.ToString()));
            pro.iFromShopID = Convert.ToInt32(cbFromShop.SelectedValue);
            pro.iToShopID = Convert.ToInt32(cbToShop.SelectedValue);
            pro.strDeliveryPerson = Utils.KillChars(txtDeliveryPerson.Text.Trim());
            pro.iTotalQuanity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
            pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());
            pro.strType = Utils.KillChars(cbType.SelectedValue.ToString());
            pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
            pro.strStatus = "N";
            if (save(pro))
            {
                txtStatus.Text = "Tạo mới";
                SetStatus("N");
                btnSave.Enabled = false;
                btnAdd.Enabled = false;
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
            }
            else
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        //Xuất kho
        if (Session["Username"] != null)
        {
            try
            {
                ProStockTransfer pro = new ProStockTransfer();
                pro.strStatus = "T";
                pro.strDeliveryPerson = Utils.KillChars(txtDeliveryPerson.Text.Trim());
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.iFromShopID = Convert.ToInt32(cbFromShop.SelectedValue);
                pro.iToShopID = Convert.ToInt32(cbToShop.SelectedValue);
                pro.iTotalQuanity = Convert.ToInt32(divGetTotalQuantity.InnerText.Trim() == "" ? "0" : divGetTotalQuantity.InnerText.Trim());
                pro.dTotalAmount = Convert.ToDouble(divGetTotalAmount.InnerText.Trim() == "" ? "0" : divGetTotalAmount.InnerText.Trim());
                #region Validate Input Data
                
                if (gvProduct.Items.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng thêm chi tiết sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                //Check ProductID có vượt quá số lượng kho
                int iProductID = 0;
                int iPackType = 0;
                db = new DBDataContext();
                foreach (GridDataItem item in gvProduct.Items)
                {
                    string[] arr = Utils.KillChars(item["ProductID"].Text.Trim()).Split('|');

                    iProductID = Convert.ToInt32(arr[0]);
                    iPackType = Convert.ToInt32(arr[1]);
                    string strQuantity = Utils.KillChars(((Label)(item.FindControl("lblQuantity"))).Text.Trim().Replace(",", ""));
                    string strProductName = Utils.KillChars(((Label)(item.FindControl("lblProductName"))).Text.Trim().Replace(",", ""));
                    var subtractWarehouse = (from c in db.Warehouses
                                             where c.ProductID == iProductID
                                                   && c.ShopID == pro.iFromShopID
                                                   && c.PackType == iPackType
                                                   && c.Status == 'A'
                                                   && c.Quantity >= Convert.ToInt32(strQuantity)
                                             select c).FirstOrDefault();
                    if (subtractWarehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng " + strProductName + " chuyển đã vượt quá số lượng của kho!");
                        cbProduct.Focus();
                        return;
                    }
                }
                #endregion
                if (save(pro))
                {
                    txtStatus.Text = "Đã xuất kho";
                    SetStatus("T");
                    btnSave.Enabled = false;
                    btnAdd.Enabled = false;
                    gvProduct.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xuất kho thành công!");
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xuất kho không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockTransfer Page-btnExport_Click-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xuất kho không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                ProStockTransfer pro = new ProStockTransfer();
                pro.strStatus = "E";
                pro.strRemark = Utils.KillChars(txtRemark.Text.Trim().ToString());
                pro.iFromShopID = Convert.ToInt32(cbFromShop.SelectedValue);
                //pro.iToShopID = Convert.ToInt32(cbToShop.SelectedValue);
                

                if (save(pro))
                {
                    txtStatus.Text = "Đã hủy";
                    SetStatus("E");
                    btnCancel.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Hủy thành công!");
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Hủy không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockTransfer Page-btnCancel_Click-Username:" + Session["Username"].ToString() + "-Error:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Hủy không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            if (ViewState["TransferWarehouseID"] != null)
            {

                delete(Convert.ToInt32(ViewState["TransferWarehouseID"]));
                SetStatus("E");
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
            }
        }
    }
}